<?php


namespace app\engine\controller;


use cmf\controller\HomeBaseController;
use think\Db;

class BillController extends HomeBaseController
{

    /**
     * 流水汇总
     * @return mixed|string
     */
    public function index()
    {

        $data = $this->request->param();
        $id = $data['id'];
        $sup = Db::name('supplier')->where(['able' => 1])->field('id,attrName')->select();
        $where = [];
        if (!empty($data['supplier'])) {
            $where['supplier'] = ['=', $data['supplier']];
        } else {
            $data['supplier'] = '';
        }
        $res = Db::name('run_bill')->where(['eid' => $id])->where($where)->order('insTime desc')->select()->toArray();
        foreach ($res as $k => $v) {
            $res[$k]['supplierName'] = Db::name('supplier')->where(['id' => $v['supplier'], 'able' => 1])->value('attrName');
            if (!is_null($v['imgs'])) {
                $res[$k]['imgs'] = 'http://' . $_SERVER['SERVER_NAME'] . $v['imgs'];
            }
        }
        $back = Db::name('run_bill')->where(['eid' => $id, 'payfor' => 1])->where($where)->sum('count');
        $sign = Db::name('run_bill')->where(['eid' => $id, 'payfor' => 2])->where($where)->sum('count');
        $com = Db::name('run_bill')->where(['eid' => $id, 'payfor' => 3])->where($where)->sum('count');
        $all = $back + $sign + $com;
        $this->assign('sup', $sup);
        $this->assign('all', $all);
        $this->assign('back', $back);
        $this->assign('sign', $sign);
        $this->assign('com', $com);
        $this->assign('res', $res);
        $this->assign('id', $id);
        $this->assign('supplier', $data['supplier']);
        return $this->fetch();
    }

    public function addBill()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $supplier = Db::name('supplier')->where(['able' => 1])->field(['id,attrName'])->select();
        $leader = Db::name('leader')->where(['eid' => $id])->field('id,name,type')->select();
        $staff = Db::name('staff')->field('id,name')->select();
        $this->assign('staff', $staff);
        $this->assign('leader', $leader);
        $this->assign('supplier', $supplier);
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 执行新增
     */
    public function doadd()
    {
        $data = $this->request->param();
        $files = request()->file('imgs');
        
        // 处理多图片上传
        if ($files) {
            $kps = [];
            foreach ($files as $file) {
                // 为每个文件创建唯一目录
                $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                // 确保目录存在
                if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                    mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                }
                
                // 生成唯一文件名
                $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                
                // 直接使用PHP的move_uploaded_file函数
                $tmpName = $file->getInfo('tmp_name');
                $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                
                if (move_uploaded_file($tmpName, $destPath)) {
                    $kps[] = '/' . $uploadDir . '/' . $newFilename;
                } else {
                    $this->error('文件上传失败');
                }
            }
            
            // 将所有图片路径合并为逗号分隔的字符串
            if (!empty($kps)) {
                $data['imgs'] = implode(',', $kps);
            }
        }
        if (empty($data['pay']) || empty($data['type']) || empty($data['supplier']) || empty($data['desc']) || empty($data['applicant']) || empty($data['unit']) || empty($data['num']) || empty($data['price']) || empty($data['payfor']) || empty($data['insTime'])) {
            $this->error('请填写完整');
        }
        $data['count'] = $data['num'] * $data['price'];
        $res = Db::name('run_bill')->insert($data);
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('添加成功');
    }

    public function del()
    {
        $data = $this->request->param();
        if (!array_key_exists('supplier', $data)) {
            $data['supplier'] = '';
        }
        $check = Db::name('run_bill')->where(['id' => $data['id']])->find();
        if (!empty($check['imgs'])) {
            $imgArray = explode(',', $check['imgs']);
            foreach ($imgArray as $img) {
                if (!empty($img)) {
                    $path = CMF_ROOT . 'public' . $img;
                    if (file_exists($path)) {
                        unlink($path);
                    }
                }
            }
        }
        $res = Db::name('run_bill')->where(['id' => $data['id']])->delete();
        if (!$res) {
            $this->error('删除失败');
        }
        $this->success('删除成功', url('index', ['supplier' => $data['supplier'], 'id' => $data['pageid']]));
    }

    public function see()
    {
        $data = $this->request->param();
        $id = $data['eid'];
        $res = Db::name('run_bill')->where(['id' => $data['id']])->find();
        
        // 处理图片路径，将单个路径或多个路径都转换为数组
        if (!empty($res['imgs'])) {
            $res['imgs'] = explode(',', $res['imgs']);
            foreach ($res['imgs'] as &$img) {
                if (!empty($img)) {
                    $img = 'http://' . $_SERVER['SERVER_NAME'] . $img;
                }
            }
        } else {
            $res['imgs'] = [];
        }
        
        $res['lname'] = Db::name('supplier')->where(['id' => $res['supplier'], 'able' => 1])->value('attrName');
        $supplier = Db::name('supplier')->where(['able' => 1])->field(['id,attrName'])->select();
        $leader = Db::name('leader')->where(['eid' => $id])->field('id,name,type')->select();
        $staff = Db::name('staff')->field('name')->select();
        $this->assign('id', $id);
        $this->assign('staff', $staff);
        $this->assign('leader', $leader);
        $this->assign('supplier', $supplier);
        $res['insTime'] = date('Y-m-d', strtotime($res['insTime']));
        $this->assign('res', $res);
        return $this->fetch();
    }


    public function doedit()
    {
        $data = $this->request->param();
        $id = $data['id'];
        unset($data['id']);
        $files = $this->request->file('imgs');
        
        if (empty($data['pay']) || empty($data['type']) || empty($data['supplier']) || empty($data['desc']) || empty($data['applicant']) || empty($data['unit']) || empty($data['num']) || empty($data['price']) || empty($data['payfor']) || empty($data['insTime'])) {
            $this->error('请填写完整');
        }
        
        // 获取当前图片列表
        $check = Db::name('run_bill')->where(['id' => $id])->find();
        $finalImgArray = [];
        
        // 处理要保留的旧图片
        if (isset($data['old_imgs']) && !empty($data['old_imgs'])) {
            $oldImages = $data['old_imgs'];
            unset($data['old_imgs']);
            
            foreach ($oldImages as $imgUrl) {
                // 从URL中提取路径
                if (strpos($imgUrl, 'http://') === 0 || strpos($imgUrl, 'https://') === 0) {
                    $parsedUrl = parse_url($imgUrl);
                    $finalImgArray[] = $parsedUrl['path'];
                } else {
                    $finalImgArray[] = $imgUrl;
                }
            }
        } else if (!empty($check['imgs']) && !isset($data['remove_imgs'])) {
            // 如果没有指定旧图片但数据库中有图片且没有要删除的图片，则使用数据库中的图片
            $imgArray = explode(',', $check['imgs']);
            foreach ($imgArray as $img) {
                if (!empty($img)) {
                    $finalImgArray[] = $img;
                }
            }
        }
        
        // 处理要删除的图片
        if (isset($data['remove_imgs']) && !empty($data['remove_imgs'])) {
            $removeImages = $data['remove_imgs'];
            unset($data['remove_imgs']);
            
            foreach ($removeImages as $imgUrl) {
                // 从URL中提取路径
                $imgPath = '';
                if (strpos($imgUrl, 'http://') === 0 || strpos($imgUrl, 'https://') === 0) {
                    $parsedUrl = parse_url($imgUrl);
                    $imgPath = $parsedUrl['path'];
                } else {
                    $imgPath = $imgUrl;
                }
                
                // 删除文件
                $path = CMF_ROOT . 'public' . $imgPath;
                if (file_exists($path)) {
                    unlink($path);
                }
                
                // 从最终图片数组中移除
                $key = array_search($imgPath, $finalImgArray);
                if ($key !== false) {
                    unset($finalImgArray[$key]);
                }
            }
        }
        
        // 处理新上传的图片
        if ($files) {
            foreach ($files as $file) {
                // 为每个文件创建唯一目录
                $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                // 确保目录存在
                if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                    mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                }
                
                // 生成唯一文件名
                $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                
                // 直接使用PHP的move_uploaded_file函数
                $tmpName = $file->getInfo('tmp_name');
                $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                
                if (move_uploaded_file($tmpName, $destPath)) {
                    $finalImgArray[] = '/' . $uploadDir . '/' . $newFilename;
                } else {
                    $this->error('文件上传失败');
                }
            }
        }
        
        // 更新图片字段
        if (!empty($finalImgArray)) {
            $data['imgs'] = implode(',', $finalImgArray);
        } else {
            $data['imgs'] = '';
        }
        $res = Db::name('run_bill')->where(['id' => $id])->update($data);
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
}
